﻿
using System;
using System.IO;
using System.Net;
using System.Security.Policy;
using System.Text;
namespace HBase {
    public class HttpRequestUrl {
        static public bool httpClientLog = false;
        static HttpRequestUrl() {
            ServicePointManager.SecurityProtocol = ( SecurityProtocolType ) 3072;
        }
        public static String httpGet(String url,bool exceptionAble=true,int time=5000) {

            String res = "";
            if (exceptionAble) {
                res = Get(url, time);
            } else {
                try {
                    res = Get(url, time);
                } catch { 
                
                }
            }
       
            
            return res;

        }

        private static String Get(String url,int time=5000) {
   
            String res = "";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Timeout = time;
            request.Method = "GET";
            request.ContentType = "text/json";//链接类型
            request.KeepAlive = false;

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (Stream s = response.GetResponseStream()) {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                res = reader.ReadToEnd();
            }
     
            return res;
        }
        public static String httpPost(String url ,string str) {
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Accept = "*/*";
            req.UserAgent = "sgj";
            req.Headers.Add("cache-control" ,"no-cache");
            req.ServicePoint.Expect100Continue = false;
            byte[] data = Encoding.UTF8.GetBytes(str);//把字符串转换为字节
            req.ContentLength = data.Length; //请求长度
            using( Stream reqStream = req.GetRequestStream() ) //获取
            {
                reqStream.Write(data ,0 ,data.Length);//向当前流中写入字节
                reqStream.Flush();
                reqStream.Close(); //关闭当前流
            }
            HttpWebResponse resp = ( HttpWebResponse ) req.GetResponse(); //响应结果
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            String res = "";
            using( StreamReader reader = new StreamReader(stream ,Encoding.UTF8) ) {
                res = reader.ReadToEnd();
            }
             
            return res;
        }
    }
}
